from app import db
from blueprints import api_blueprint
from blueprints.personal.api.information import PersonalInformation
from tools.decorate import pack_session
from tools.image import ImageDefault
from tools.model import QueryOneInstance, UpdateInstance
from tools.response import Response, ResponsePostJson

class PersonalIdentity(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    uid = db.Column(db.Integer, nullable=False)
    role = db.Column(db.String(50), default='访客')
    image = db.Column(db.Text, default=lambda :ImageDefault())
    published = db.Column(db.Boolean, default=False)
    checked = db.Column(db.Boolean, default=False)
    passed = db.Column(db.Boolean, default=False)
    reason = db.Column(db.String(300), default='无')

@api_blueprint.route('/personal/PersonalIdentity/pass/<int:uid>', methods=['GET'])
def pass_personal_identity(uid):
    instance = QueryOneInstance(PersonalIdentity, {'uid': uid})
    instance.checked = True
    instance.passed = True
    UpdateInstance(instance)

    info = QueryOneInstance(PersonalInformation, {'uid': uid})
    info.role = instance.role
    UpdateInstance(info)

    return Response("已通过")

@api_blueprint.route('/personal/PersonalIdentity/unpass/<int:uid>', methods=['POST'])
def unpass_personal_identity(uid):
    def cb(json):
        instance = QueryOneInstance(PersonalIdentity, {'uid': uid})
        instance.checked = True
        instance.passed = False
        instance.reason = json['reason']
        UpdateInstance(instance)
        return Response(f"未通过, 原因: {instance.reason}")
    return ResponsePostJson(['reason'], cb)

@api_blueprint.route('/personal/PersonalIdentity/publish', methods=['POST'])
@pack_session
def publish_personal_identity(data):
    def cb(json):
        instance = QueryOneInstance(PersonalIdentity, {'uid': data['session']['uid']})

        if instance.checked and instance.passed:
            return Response("已通过认证,请勿提交")

        instance.published = True
        instance.checked = False
        instance.passed = False
        UpdateInstance(instance, json)
        return Response("已提交认证")
    return ResponsePostJson(['role', 'image'], cb)